<template>
  <div class="cycle-select-container">
    <div class="cycle-select-container_top"></div>
    <i-form ref="form" :items="items" v-model="item" :rules="rules">
      <template slot="weekday">
        <el-form-item label="星期选择" prop="daysOfWeek">
          <el-checkbox-group
            v-model="item.daysOfWeek"
            @change="handleDaysChange"
          >
            <el-checkbox-button
              v-for="day in weekdays"
              :key="day.label"
              :label="day.label"
              :disabled="judgeDisabled(day.label)"
            >
              {{ day.text }}
            </el-checkbox-button>
          </el-checkbox-group>
        </el-form-item>
      </template>
      <template slot="timefragment">
        <el-form-item label="时间段选择" prop="hours">
          <div class="cycle-select_timefragment_wrapper">
            <div
              class="cycle-select_timefragment_item"
              v-for="(hour, index) in item.hours"
              :key="index"
            >
              <date-picker
                v-model="item.hours[index]"
                range
                confirm
                :minute-step="1"
                format="HH:mm"
                value-type="format"
                type="time"
                placeholder="选择时间，可输入(00:00 ~ 00:00)，带波浪号"
                @change="handleHoursChange"
              ></date-picker>
              <i
                class="el-icon-remove cycle-select-button"
                @click="
                  () => {
                    deleteTimeFragment(index)
                  }
                "
              >
              </i>
            </div>
            <i
              class="el-icon-circle-plus cycle-select-button"
              v-if="item.hours.length < 3"
              @click="
                () => {
                  addTimeFragment()
                }
              "
            >
            </i>
          </div>
        </el-form-item>
      </template>
    </i-form>
    <div
      v-if="showDelete"
      class="cycle-select-container_delete"
      @click="handleDelete"
    >
      <i class="el-icon-delete"> </i>
    </div>
  </div>
</template>
<script>
import DatePicker from 'vue2-datepicker'
import 'vue2-datepicker/index.css'
import 'vue2-datepicker/locale/zh-cn'
import _ from 'lodash'

export default {
  name: 'CycleSelect',
  components: { DatePicker },
  props: {
    selectedDays: {
      type: Array,
      required: true,
    },
    item: {
      type: Object,
      required: true,
    },
    showDelete: {
      type: Boolean,
      required: true,
    },
  },
  watch: {
    selectedDays: {
      handler(val, oldval) {
        if (_.isEqual(val, oldval)) return
        this.resetKey += 1
      },
    },
    'item.daysOfWeek': {
      handler(val, oldVal) {
        if (_.isEqual(val, oldVal) || !Array.isArray(val)) return
        if (val.length < 1) this.item.hours = []
      },
    },
    'item.hours': {
      handler(val, oldVal) {
        this.$refs.form.validate((valid) => {
          if (!valid) return
        })
        if (_.isEqual(val, oldVal)) return
      },
      deep: true,
    },
  },
  data() {
    return {
      value: '',
      resetKey: 1,
      weekdays: [
        {
          label: 1,
          text: '星期一',
        },
        {
          label: 2,
          text: '星期二',
        },
        {
          label: 3,
          text: '星期三',
        },
        {
          label: 4,
          text: '星期四',
        },
        {
          label: 5,
          text: '星期五',
        },
        {
          label: 6,
          text: '星期六',
        },
        {
          label: 7,
          text: '星期天',
        },
      ],
      items: [
        {
          slot: 'weekday',
        },
        {
          slot: 'timefragment',
        },
      ],
      rules: {
        hours: [
          {
            validator: (value, rules, callback) => {
              let itemLength = this.item.hours.length
              if (itemLength > 0) {
                let validArr = []
                this.item.hours.forEach((item) => {
                  for (let i = 0; i < item.length; i++) {
                    validArr.push(item[i])
                  }
                })

                if (validArr.includes(null)) {
                  callback(new Error('请填写完整时间段'))
                } else if (!this.isSorted(validArr)) {
                  callback(new Error('有起始时间等于结束时间的段，请检查'))
                } else if (!this.isCoverd(this.item.hours)) {
                  callback(new Error('有交叠的时间段，请检查项目'))
                } else {
                  callback()
                }
              } else {
                callback()
              }
            },
          },
        ],
        daysOfWeek: [
          {
            validator: (value, rules, callback) => {
              if (
                !Array.isArray(this.item.daysOfWeek) ||
                this.item.daysOfWeek.length < 1
              ) {
                callback(new Error('至少选择一天作为停用周期'))
              } else {
                callback()
              }
            },
          },
        ],
      },
    }
  },
  mounted() {},
  computed: {},
  methods: {
    isSorted(arr) {
      for (let i = 0; i < arr.length - 1; i++) {
        if (i % 2 == 0 && arr[i] === arr[i + 1]) {
          return false
        }
      }

      return true
    },
    isCoverd(arr) {
      if (arr.length < 2) return true
      for (let i = 0; i < arr.length - 1; i++) {
        for (let j = i + 1; j < arr.length; j++) {
          let max = arr[i][0] >= arr[j][0] ? arr[i][0] : arr[j][0]
          let min = arr[i][1] <= arr[j][1] ? arr[i][1] : arr[j][1]

          if (max <= min) return false
        }
      }

      return true
    },
    judgeDisabled(label) {
      if (this.item.daysOfWeek.includes(label)) return false

      return this.selectedDays.includes(label)
    },
    handleDaysChange(val) {
      this.$emit('dayschange', val)
    },
    handleDelete() {
      this.$emit('delete', this.item.daysOfWeek)
    },
    handleHoursChange() {
      this.$refs.form.validate((valid) => {
        if (!valid) return
      })
    },
    addTimeFragment() {
      if (this.item.daysOfWeek.length < 1) {
        this.$message({
          showClose: true,
          message: '选择某星期之后，才可以添加时长限制！',
          type: 'warning',
        })
        return
      }

      this.item.hours.push([null, null])
    },
    deleteTimeFragment(index) {
      this.item.hours.splice(index, 1)
    },
    // getValue() {
    //   return {
    //     dayChecked: this.dayChecked,
    //     fragments: this.fragments
    //   }
    // },
    validateValue() {
      let validValue = false
      this.$refs.form.validate((valid) => {
        validValue = valid
      })

      return validValue
    },
  },
}
</script>
<style lang="scss" scoped>
.cycle-select-container {
  border: 1px solid #ddd1e8;
  position: relative;
  margin-bottom: 20px;

  .cycle-select-container_top {
    height: 32px;
    background: #f7f1fc;
    margin-bottom: 10px;
  }

  .cycle-select-container_delete {
    width: 30px;
    height: 30px;
    background: #f7f1fc;
    text-align: center;
    line-height: 30px;
    border-radius: 50%;
    cursor: pointer;
    position: absolute;
    right: 20px;
    top: 40px;
  }

  .cycle-select-button {
    padding: 0 4px;
    width: 20px;
    height: 20px;
    font-size: 20px;
    color: rgb(109, 214, 138);
    cursor: pointer;
  }

  .cycle-select_timefragment_wrapper {
    display: flex;
    align-items: center;
    height: 40px;
  }

  .cycle-select_timefragment_item {
    height: 100%;
    display: flex;
    align-items: center;
    padding-right: 20px;
  }
}
</style>
